//
//  IGLinkiGalleryBluetoothVC.m
//  jingdongfang
//
//  Created by boectoswteam on 2018/5/21.
//  Copyright © 2018年 BOE-SBG-CTO. All rights reserved.
//

#import "IGLinkiGalleryBluetoothVC.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import <CoreBluetooth/CBService.h>
#import "IGiGalleryBindApi.h"

#define SERVICE_UUID                @"1000" //服务
#define WRITE_CHARACTERISTIC_UUID   @"1001" //写特征
#define READ_CHARACTERISTIC_UUID    @"1002"//读特征

@interface IGLinkiGalleryBluetoothVC ()<CBCentralManagerDelegate,CBPeripheralDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic, strong) CBCentralManager *centralManager;   //中心管理器
@property (nonatomic, strong) CBPeripheral *peripheral;//外设
@property (nonatomic, strong) CBCharacteristic * writeCharacteristic;//写特征
@property (nonatomic, strong) CBCharacteristic * readCharacteristic; //读特征
@property (nonatomic, strong) NSMutableArray *serviceArray;//服务数组
@property (nonatomic, strong) NSMutableArray *characterArray;//特征数组

@property (nonatomic, strong) NSDictionary *menuDictionay;
@property (nonatomic, strong) NSMutableArray *iGalleryDeviceArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *menuView;
@property (nonatomic, strong) IGiGalleryBindApi *bindApi; //绑定Api
@property (nonatomic, strong) UITextField *wifiTF;
@property (nonatomic, strong) UITextField *pwdTF;
@end

@implementation IGLinkiGalleryBluetoothVC

#pragma mark - lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor mainBackgroundColor];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(30, 66, KSCREENWIDTH - 60, 40);
    btn.backgroundColor = [UIColor greenColor];
    [btn setTitle:@"链接我的画屏" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(linkMyBluetooth) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn1.frame = CGRectMake(30, 350, KSCREENWIDTH - 60, 40);
    [btn1 setTitle:@"发送数据到画屏" forState:UIControlStateNormal];
    [btn1 setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [btn1 addTarget:self action:@selector(writeDataToiGallery) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:btn1];
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.menuView];
    
    
}

-(void)linkMyBluetooth{
    self.centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue()];
}

-(void)sendDataToDevice{
    
}

#pragma mark - CBCentralManagerDelegate & CBPeripheralDelegate

/*判断手机蓝牙状态*/
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
    
    NSLog(@"central.state:%ld",(long)central.state);
//    if (@available(iOS 11.0,*)) {
        if (central.state == CBManagerStatePoweredOn) {
            //蓝牙可用,扫描周围所有蓝牙设备
            //        [central scanForPeripheralsWithServices:@[CBUUID UUIDWithString:@""] options:nil];
            [central scanForPeripheralsWithServices:nil options:nil];
        } else if (central.state == CBManagerStateUnsupported){
            //该设备不支持蓝牙
        } else if (central.state == CBManagerStatePoweredOff){
            
            //蓝牙已关闭
        }
//    } else {
//        if (central.state == CBCentralManagerStatePoweredOn) {
//            //蓝牙可用,扫描周围所有蓝牙设备
//            //        [central scanForPeripheralsWithServices:@[CBUUID UUIDWithString:@""] options:nil];
//            [central scanForPeripheralsWithServices:nil options:nil];
//        } else if (central.state == CBCentralManagerStateUnsupported){
//            //该设备不支持蓝牙
//        } else if (central.state == CBCentralManagerStatePoweredOff){
//
//            //蓝牙已关闭
//        }
//    }
}

/*发现符合要求的外设，回调*/
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
//    NSLog(@"peripheral:%@",peripheral.name);
    
    //过滤链接外设
//    if ([peripheral.name isEqualToString:@"boeigallery"]) {
//        [central connectPeripheral:peripheral options:nil];
//        //对外设对象进行强引用
//        self.peripheral = peripheral;
//    }
    
    [self.iGalleryDeviceArray addObject:peripheral];
    [self.tableView reloadData];
}

/*链接外设成功*/
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    NSLog(@"连接成功");
    [self presentMessageTips:@"画屏连接成功"];
    //停止扫描
    [self.centralManager stopScan];
    //设置代理
    peripheral.delegate = self;
    
    //根据UUID来寻找服务
    [peripheral discoverServices:@[[CBUUID UUIDWithString:SERVICE_UUID]]];
    
}

/*链接外设失败的回调*/
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"链接失败");
}

/*断开链接*/
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    //断开链接可以设置重新链接
    [central connectPeripheral:peripheral options:nil];
}



#pragma mark - CBPeripheralDelegate
/*发现服务*/
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    //遍历外设中的所有服务
//    for (CBService * service in peripheral.services) {
//        NSLog(@"所有服务:%@",service);
//        [self.serviceArray addObject:peripheral.services];
//    }
    
    //这里仅有一个服务，所以直接获取
    CBService *service = peripheral.services.lastObject;
    //根据UUID寻找服务中的特征
    [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:READ_CHARACTERISTIC_UUID],[CBUUID UUIDWithString:WRITE_CHARACTERISTIC_UUID]] forService:service];
}

/*发现特征回调*/
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    //遍历出所需要的特征
    for (CBCharacteristic * characteristic in service.characteristics) {
        NSLog(@"所有特征：%@",characteristic);
        //从外设开发人员那里拿到不同特征的UUID，不同特征做不同事情，比如有读取数据的特征，也有写入数据的特征
//        if ([characteristic.UUID isEqual:@"1001"]) {
//            self.writeCharacteristic = characteristic.copy;
//        }
//        if ([characteristic.UUID isEqual:@"1002"]) {
//            self.readCharacteristic = characteristic.copy;
//        }
    }
    
    self.writeCharacteristic = service.characteristics[0];
    self.readCharacteristic = service.characteristics[1];
    //这里只获取一个特征，写入数据的时候需要用到这个特征
//    self.characteristic = service.characteristics.lastObject;
    
    //直接读取这个特征数据，会调用didUpdateValueForCharacteristic
//    [peripheral readValueForCharacteristic:self.characteristic];
    [peripheral readValueForCharacteristic:self.readCharacteristic];
    //订阅通知   订阅成功后，手机app就可以监控外设中这个特征值的变化了
    [peripheral setNotifyValue:YES forCharacteristic:self.readCharacteristic];
}


/*订阅状态的改变*/
-(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error) {
        NSLog(@"订阅失败");
        NSLog(@"%@",error.localizedDescription);
    }
    if (characteristic.isNotifying) {
        NSLog(@"订阅成功");
    } else {
        NSLog(@"取消订阅");
    }
}


/*接收到数据回调*/
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    //拿到外设发送过来的数据
    NSData *data = characteristic.value;
    NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"接收到外设的数据:%@",string);
    if ([string hasPrefix:@"&%"]&& [string hasSuffix:@"&%"]) {
        //获取画屏设备mac地址,做绑定请求
        NSString *string1 = [string stringByReplacingOccurrencesOfString:@"&" withString:@""];
        NSString *macId = [string1 stringByReplacingOccurrencesOfString:@"%" withString:@""];
        [self bindiGalleryWithMacId:macId];
    }
}


/*中心设备向外设写入数据*/
-(void)writeDataToiGallery{
    NSString *writeString = @"C9";
    //转data类型来写入数据
    NSData *data = [self hexToBytes:writeString];
//    NSData *data = [self hexString:writeString];
    //根据上面的特征 self.characteristic来写入数据

    [self.peripheral writeValue:data forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

/*写入数据回调*/
-(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    NSLog(@"写入成功");
}

/*读取数据*/
-(void)readDataFromDevice{
    //从外设读取数据
    [self.peripheral readValueForCharacteristic:self.readCharacteristic];
}

#pragma mark - UITableViewDelegate && UITableViewDateSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.iGalleryDeviceArray.count?self.iGalleryDeviceArray.count:0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cellID";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    CBPeripheral *peripheral = self.iGalleryDeviceArray[indexPath.row];
    cell.textLabel.text = peripheral.name!=nil?peripheral.name:@"NO-Name";
//    cell.textLabel.text = @"123";
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CBPeripheral *peripheral = self.iGalleryDeviceArray[indexPath.row];
    if ([peripheral.name hasPrefix:@"boe"]) {
        self.peripheral = peripheral;
        [self.centralManager connectPeripheral:peripheral options:nil];
    } else {
        [self presentMessageTips:@"非画屏设备，无法连接！！！"];
    }
    
}

#pragma mark - UITextFieldDelegate
-(void)textFieldDidEndEditing:(UITextField *)textField{
    [textField resignFirstResponder];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.wifiTF resignFirstResponder];
    [self.pwdTF resignFirstResponder];
}

#pragma mark - events

-(void)bindiGalleryWithMacId:(NSString *)macId{
    __weak typeof(self) weakSelf = self;
    self.bindApi = [[IGiGalleryBindApi alloc]initWithMacId:macId title:@"" type:IGiGalleryTypeiGallery];
    [self.bindApi startWithDecodeClass:[IGiGalleryBindResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        IGiGalleryBindResp *response = responseObject;
        IGiGalleryBindModel *model = response.data;
        [weakSelf presentMessageTips:model.msg];
    }];
    
}

//将NSString转换成十六进制的字符串则可使用如下方式:
+ (NSString *)convertStringToHexStr:(NSString *)str {
    if (!str || [str length] == 0) {
        return @"";
    }
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}

- (NSData *)hexToBytes:(NSString *)str
{
    NSMutableData* data = [NSMutableData data];
    int idx;
    for (idx = 0; idx+2 <= str.length; idx+=2) {
        NSRange range = NSMakeRange(idx, 2);
        NSString* hexStr = [str substringWithRange:range];
        NSScanner* scanner = [NSScanner scannerWithString:hexStr];
        unsigned int intValue;
        [scanner scanHexInt:&intValue];
        [data appendBytes:&intValue length:1];
    }
    return data;
}


-(NSData *)hexString:(NSString *)hexString {
    int j=0;
    Byte bytes[20];
    ///3ds key的Byte 数组， 128位
    for(int i=0; i<[hexString length]; i++)
    {
        int int_ch;  /// 两位16进制数转化后的10进制数
        
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        else
            int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        else
            int_ch2 = hex_char2-87; //// a 的Ascll - 97
        
        int_ch = int_ch1+int_ch2;
        NSLog(@"int_ch=%d",int_ch);
        bytes[j] = int_ch;  ///将转化后的数放入Byte数组里
        j++;
    }
    
    NSData *newData = [[NSData alloc] initWithBytes:bytes length:20];
    
    return newData;
}


-(void)menuBtnClick:(UIButton*)btn{
    NSString *title = btn.titleLabel.text;
    NSString *menu = self.menuDictionay[title];
    NSData *data = [self hexToBytes:menu];
    [self.peripheral writeValue:data forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

-(void)sendWifi{
    if (self.wifiTF.text.length == 0 || self.pwdTF.text.length == 0) {
        [self presentMessageTips:@"请输入wifi账号密码"];
        return;
    }
    
    NSString *wifi = [NSString stringWithFormat:@"*%%%@*%%",self.wifiTF.text];
    NSString *pwd = [NSString stringWithFormat:@"#%%%@#%%",self.pwdTF.text];
    NSData *wifiData = [wifi dataUsingEncoding:NSUTF8StringEncoding];
    NSData *pwdData = [pwd dataUsingEncoding:NSUTF8StringEncoding];
    [self.peripheral writeValue:wifiData forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
    [self.peripheral writeValue:pwdData forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

#pragma mark - set & get

-(NSMutableArray *)serviceArray{
    if (!_serviceArray) {
        _serviceArray = [NSMutableArray array];
    }
    return _serviceArray;
}

-(NSMutableArray *)characterArray{
    if (!_characterArray) {
        _characterArray = [NSMutableArray array];
    }
    return _characterArray;
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 120, KSCREENWIDTH, 200) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor lightGrayColor];
    }
    return _tableView;
}

-(UIView *)menuView{
    if (!_menuView) {
        _menuView = [[UIView alloc]init];
        _menuView.frame = CGRectMake(0, 350, KSCREENWIDTH, KSCREENHEIGHT - 400);
        _menuView.backgroundColor = [UIColor yellowColor];
        NSArray *allkeys = self.menuDictionay.allKeys;
        
        for (int i = 0; i<allkeys.count; i++) {
            
            NSInteger  X = i/4;
            NSInteger  Y = i%4;
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(KSCREENWIDTH/4 * X, Y*40, KSCREENWIDTH/4, 40);
            [btn setTitle:allkeys[i] forState:UIControlStateNormal];
            [btn setBackgroundColor:[UIColor mainRandomColor]];
            [btn addTarget:self action:@selector(menuBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            [_menuView addSubview:btn];
        }
        
        
        UILabel *wifiLabel = [[UILabel alloc]init];
        wifiLabel.frame = CGRectMake(20, 180, 40, 30);
        wifiLabel.text = @"wifi:";
        wifiLabel.textColor = [UIColor blackColor];
        [_menuView addSubview:wifiLabel];
        
        UITextField *wifi = [[UITextField alloc]init];
        wifi.delegate = self;
        wifi.frame = CGRectMake(80, 180, 200, 30);
        wifi.placeholder = @"wifi账号";
        self.wifiTF = wifi;
        [_menuView addSubview:wifi];
        
        
        UILabel *pwdLabel = [[UILabel alloc]init];
        pwdLabel.frame = CGRectMake(20, 210, 40, 30);
        pwdLabel.text = @"pwd:";
        pwdLabel.textColor = [UIColor blackColor];
        [_menuView addSubview:pwdLabel];
        
        UITextField *pwd = [[UITextField alloc]init];
        pwd.delegate = self;
        pwd.frame = CGRectMake(80, 210, 200, 30);
        pwd.secureTextEntry = YES;
        pwd.placeholder = @"wifi密码";
        self.pwdTF = pwd;
        [_menuView addSubview:pwd];
        
        
        UIButton *wifiBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        wifiBtn.frame = CGRectMake(290, 195, 40, 30);
        wifiBtn.backgroundColor = [UIColor blackColor];
        [wifiBtn setTitle:@"wifi设置" forState:UIControlStateNormal];
        [wifiBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [wifiBtn addTarget:self action:@selector(sendWifi) forControlEvents:UIControlEventTouchUpInside];
        [_menuView addSubview:wifiBtn];
    }
    return _menuView;
}

-(NSMutableArray *)iGalleryDeviceArray{
    if (!_iGalleryDeviceArray) {
        _iGalleryDeviceArray = [NSMutableArray array];
    }
    return _iGalleryDeviceArray;
}

-(NSDictionary *)menuDictionay{
    if (!_menuDictionay) {
        _menuDictionay = @{@"横屏":@"A1",@"竖屏":@"A2",@"中文":@"B1",@"英文":@"B2",@"Power":@"C1",@"HDMI":@"C2",@"IG":@"C3",@"UP":@"C4",@"DOWN":@"C5",@"LEFT":@"C6",@"RIGHT":@"C7",@"OK":@"C8",@"MENU":@"C9",@"BACK":@"CA",@"绑定设备":@"F1"};
    }
    return _menuDictionay;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
